package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;

    @Override
    public Cart save(Cart cart) {
        //1.判断cart是否存在

        LambdaQueryWrapper<Cart>wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(cart.getDishId() != null,Cart::getDishId,cart.getDishId());
        wrapper.eq(cart.getSetmealId() !=null,Cart::getSetmealId,cart.getSetmealId());
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());

        Cart cart1 = cartMapper.selectOne(wrapper);//最多返回一条

        //如果已经在购物车，那么数量+1，不在就创建新的报讯到数据库
        if (cart1 != null){
            cart1.setNumber(cart1.getNumber()+1);
            cartMapper.updateById(cart1);
            return cart1;//返回继续判断

        }else {
            cart.setUserId(UserHolder.get().getId());//创建新的
            cart.setNumber(1);
            cart.setCreateTime(new Date());
            cartMapper.insert(cart);
            return cart;
        }
    }
    @Override
    public List<Cart> findList(){
        //查询当前用户的购物车
        LambdaQueryWrapper<Cart>wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId());
        return cartMapper.selectList(wrapper);
    }
    //减少
    @Override
    public Cart sub( ){
        //判断购物车中的数量是否大于一
        LambdaQueryWrapper <Cart>wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(Cart::getUserId,UserHolder.get().getId());

        Cart cart2 = cartMapper.selectOne(wrapper2);
//        for (int i = 1000; i >0 ; i--) {
//            cart2.setNumber(cart2.getNumber()-1);
//        }

        return cart2;

    }

    //清除购物车
    @Override
    public void clean(){
        //根据用户ID删除
        LambdaQueryWrapper<Cart>wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        cartMapper.delete(wrapper);

    }
}
